package com.credithc.signature.common.service;

import com.credithc.baseserv.pageHelper.PageInfo;
import com.credithc.signature.common.constant.CacheConstant;
import com.credithc.signature.common.constant.ManagerConstant;
import com.credithc.signature.common.mapper.FddSealInfoMapper;
import com.credithc.signature.common.mapper.HistoryOfficialSealTemplateMapper;
import com.credithc.signature.common.mapper.SealChannelMapper;
import com.credithc.signature.common.mapper.TemplateExtMapper;
import com.credithc.signature.common.mapper.TemplateHistoryMapper;
import com.credithc.signature.common.mapper.TemplateMapper;
import com.credithc.signature.common.po.Channel;
import com.credithc.signature.common.po.Dictionary;
import com.credithc.signature.common.po.FddSealInfo;
import com.credithc.signature.common.po.HistoryOfficialSealTemplate;
import com.credithc.signature.common.po.OfficialSealTemplate;
import com.credithc.signature.common.po.SealInfo;
import com.credithc.signature.common.po.Template;
import com.credithc.signature.common.po.TemplateExt;
import com.credithc.signature.common.po.TemplateHistory;
import com.credithc.signature.common.ro.manager.TemplateRo;
import com.credithc.signature.common.utils.CacheUtil;
import com.credithc.signature.common.utils.GeneralUtil;
import com.credithc.signature.common.utils.ManagerBeanUtil;
import com.credithc.signature.common.utils.PageUtils;
import com.credithc.signature.common.vo.manager.DictionaryVo;
import com.credithc.signature.common.vo.manager.TemplateVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
@Service
public class TemplateService {

    @Autowired
    private TemplateMapper templateMapper;


    @Autowired
    private TemplateHistoryMapper templateHistoryMapper;

    @Autowired
    private HistoryOfficialSealTemplateMapper historyOfficialSealTemplateMapper;

    @Autowired
    private TemplateExtMapper templateExtMapper;

    @Autowired
    private ChannelService channelService;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private SealInfoService sealInfoService;

    @Autowired
    private OfficialSealTemplateService officialSealTemplateService;

    @Autowired
    FddSealInfoMapper fddSealInfoMapper;

    /**
     * 根据条件模板
     *
     * @param example
     * @return
     */
    public List<Template> selectByExample(Object example) {
        return templateMapper.selectByExample(example);
    }

    /**
     * 查询模板信息--缓存
     *
     * @param templateNo
     * @return
     */
    public Template selectCacheByTemplateNo(String templateNo) {
        Template cacheTemplate = null;
        try {
            cacheTemplate = CacheUtil.getTemplateCache().get(CacheConstant.TEMPLATE_PREFIX + templateNo);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return cacheTemplate;
    }

    /**
     * 查询模板信息
     *
     * @param templateNo
     * @return
     */
    public Template selectByTemplateNo(String templateNo) {
        Example templateExample = new Example(Template.class);
        Example.Criteria templateCriteria = templateExample.createCriteria();
        templateCriteria.orEqualTo("templateNo", templateNo);
        templateCriteria.orEqualTo("templateMappingNo", templateNo);
        Example.Criteria criteria = templateExample.createCriteria();
        criteria.andEqualTo("auditStatus", ManagerConstant.AUDITPASS);
        templateExample.and(criteria);
        Template template = templateMapper.selectOneByExample(templateExample);
        return template;
    }

    /**
     * 查询所有
     *
     * @param templateRo
     * @return
     */
    public PageInfo<TemplateVo> queryAll(TemplateRo templateRo) {
        if (StringUtils.isNotBlank(templateRo.getChannelIds())) {
            log.info("查询所有模板channelIds=[" + templateRo.getChannelIds() + "]");
            //修改模板的状态
            if (templateRo.getTemplateStatus() != null) {
                if (templateRo.getTemplateStatus().equals(ManagerConstant.Enable)) {
                    templateRo.setEnableStatus(ManagerConstant.Enable);
                } else {
                    templateRo.setDisableStatus(ManagerConstant.Enable);
                }
            }
            PageUtils.setPageNo(templateRo);
            List<Template> templates = templateMapper.listByParamsAndPage(templateRo);
            int count = templateMapper.countByParamsAndPage(templateRo);
            List<TemplateVo> vos = buildPos(templates);
            return new PageInfo<>(vos, count, templateRo.getPageNo(), templateRo.getPageSize());
        } else {
            return new PageInfo<>(null, 0, templateRo.getPageNo(), templateRo.getPageSize());
        }
    }

    /**
     * 查询单条
     *
     * @param id
     * @return
     */
    public TemplateVo queryOne(Long id) {
        Template template = templateMapper.selectByPrimaryKey(id);
        TemplateVo templateVo = new TemplateVo();
        return convertPotoVo(template, templateVo);
    }

    /**
     * 根据channelId查询多条
     *
     * @param channelId
     * @return
     */
    public List<Template> queryListBychannelId(Integer channelId) {
        Template template = new Template();
        template.setChannelId(channelId);
        List<Template> templates = templateMapper.select(template);
        return templates;
    }

    /**
     * 导出模板
     *
     * @param ids
     * @param response
     */
    public void export(String ids, HttpServletResponse response, String className) {
        if (ids.split(",").length > 1) {
            //批量下载
            batchDownload(ids, response, className);
        } else {
            //单个文件下载
            download(ids, response, className);
        }
    }

    /**
     * 批量下载
     *
     * @param ids
     * @param response
     */
    private void batchDownload(String ids, HttpServletResponse response, String className) {
        try {
            ZipOutputStream os = new ZipOutputStream(response.getOutputStream());
            buildResponse(response, ManagerConstant.ZIPNAME);
            String[] split = ids.split(",");
            for (String id : split) {
                TemplateExt templateExt = templateExtMapper.selectByPrimaryKey(id);
                if (templateExt == null) {
                    continue;
                }
                byte[] data = templateExt.getTemplateData();
                String singleFile = buildFileName(id, templateExt, className);
                os.putNextEntry(new ZipEntry(singleFile));
                os.write(data);
            }
            os.closeEntry();
            os.flush();
            os.close();
        } catch (Exception e) {
            log.error("批量下载模板文件发送异常", e);
        }
    }

    /**
     * 单文件下载
     *
     * @param ids
     * @param response
     */
    private void download(String ids, HttpServletResponse response, String className) {
        TemplateExt templateExt = templateExtMapper.selectByPrimaryKey(ids);
        byte[] data = templateExt.getTemplateData();
        String fileName = buildFileName(ids, templateExt, className);
        buildResponse(response, fileName);
        OutputStream os;
        try {
            os = response.getOutputStream();
            os.write(data);
            os.flush();
        } catch (Exception e) {
            log.error("下载模板文件发生异常", e);
        }
    }

    /**
     * 上传模板
     *
     * @param file
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public Integer upload(MultipartFile file) {
        TemplateExt templateExt = new TemplateExt();
        try {
            String fileName = file.getOriginalFilename();
            if (StringUtils.isNotEmpty(fileName)) {
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                templateExt.setExtName(suffix);
            }
            templateExt.setTemplateData(file.getBytes());
            templateExt.setCreateTime(new Date());
            templateExt.setUpdateTime(new Date());
            templateExtMapper.insertFile(templateExt);
            return templateExt.getId();
        } catch (IOException e) {
            log.error("上传模板文件发生异常", e);
        }
        return null;
    }

    /**
     * 新增摸吧
     *
     * @param templateRo
     */
    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.REQUIRED)
    public void saveTemplate(TemplateRo templateRo) {
        Template template = new Template();
        try {
            templateRo.setPageNo(1);
            templateRo.setPageSize(1);
            String channelNo = templateRo.getChannelNo();
            Channel channel = channelService.selectChannelByCode(channelNo);
            //查询最新的模板编号，然后生成新的模板编号
            Example example = new Example(Template.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andLike("templateNo", "QZ%");
            example.setOrderByClause("id desc");
            List<Template> templates = templateMapper.selectByExample(example);
            BeanUtils.copyProperties(templateRo, template);
            buildRefId(templateRo, template);
            template.setTemplateNo(GeneralUtil.buildTemplateNo((templates.size() == 0) ? null : templates.get(0).getTemplateNo(), channel.getChannelAlias()));
            template.setChannelId(channel.getId());
            template.setVersion(ManagerConstant.INITVERSION);
            template.setAuditStatus(ManagerConstant.UNAUDITED);
            template.setTemplateStatus(ManagerConstant.DISABLE);
            template.setCreateTime(new Date());
            template.setUpdateTime(new Date());
            templateMapper.insert(template);
            //处理公章规则号
            if (!ManagerConstant.PERSONAL.equals(templateRo.getSealType())) {
                insertOfficialSeal(templateRo.getOfficialSealId(), template.getTemplateNo());
            }
        } catch (Exception e) {
            log.error("新增模板发生异常", e);
        }
    }

    /**
     * 封装refId
     *
     * @param templateRo
     * @param template
     */
    private void buildRefId(TemplateRo templateRo, Template template) {
        //文件上传
        if (ManagerConstant.UPLOAD.equals(templateRo.getResource()) && StringUtils.isNotEmpty(templateRo.getRefId())) {
            template.setRefId(Integer.valueOf(templateRo.getRefId()));
        } else if (ManagerConstant.ONLINE.equals(templateRo.getResource())) {
            insertFileData(templateRo, template);
        }
    }


    /**
     * 新增公章规则号
     *
     * @param officialSealId
     * @param templateNo
     */
    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.REQUIRED)
    public void insertOfficialSeal(String[] officialSealId, String templateNo) {
        if (officialSealId == null) {
            throw new RuntimeException("公章规则号为空");
        }
        for (String sealCode : officialSealId) {
            OfficialSealTemplate sealTemplate = new OfficialSealTemplate();
            sealTemplate.setTemplateNo(templateNo);
            sealTemplate.setOfficialSealCode(sealCode);
            officialSealTemplateService.insert(sealTemplate);
        }
    }

    /**
     * 查询签章类型
     *
     * @return
     */
    public List<DictionaryVo> querySealTypes() {
        List<Dictionary> dictionaryPos = dictionaryService.selectByType(ManagerConstant.SEAL_TYPE);
        List<DictionaryVo> list = new ArrayList<>();
        dictionaryPos.forEach(po -> {
            DictionaryVo vo = new DictionaryVo();
            BeanUtils.copyProperties(po, vo);
            list.add(vo);
        });
        return list;
    }

    /**
     * 查询公章主体
     *
     * @return
     */
    public List<DictionaryVo> queryOfficialSeal() {
        List<Dictionary> dictionaryPos = dictionaryService.selectByType(ManagerConstant.OFFICIAL_TYPE);
        List<DictionaryVo> list = new ArrayList<>();
        dictionaryPos.forEach(po -> {
            DictionaryVo vo = new DictionaryVo();
            BeanUtils.copyProperties(po, vo);
            list.add(vo);
        });
        return list;
    }

    /**
     * 删除记录
     *
     * @param id
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public void remove(Long id) {
        try {
            templateMapper.deleteByPrimaryKey(id);
        } catch (Exception e) {
            log.error("删除模板发生异常", e);
        }
    }


    /**
     * 更新模板
     *
     * @param templateRo
     */
    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.REQUIRED)
    public void updateTemplate(TemplateRo templateRo) {
        try {
            Template template = new Template();
            BeanUtils.copyProperties(templateRo, template);
            template.setUpdateTime(new Date());
            buildRefId(templateRo, template);
            //模板内容不为空，则更新到历史表
            if (ManagerConstant.UPLOAD.equals(templateRo.getResource()) && StringUtils.isNotEmpty(templateRo.getRefId())) {
                template.setRefId(Integer.valueOf(templateRo.getRefId()));
                updateTemplateHistory(template);
                template.setVersion(GeneralUtil.buildVersion(templateRo));
            } else {
                if (StringUtils.isNotEmpty(templateRo.getFileData())) {
                    insertFileData(templateRo, template);
                    updateTemplateHistory(template);
                    template.setVersion(GeneralUtil.buildVersion(templateRo));
                }
            }
            templateMapper.updateByPrimaryKeySelective(template);
            //处理公章规则号
            if (!ManagerConstant.PERSONAL.equals(templateRo.getSealType())) {
                updateOfficialSeal(templateRo.getOfficialSealId(), template.getTemplateNo());
            }
        } catch (Exception e) {
            log.error("更新模板发生异常", e);
        }
    }

    /**
     * 保存文件
     *
     * @param templateRo
     * @param template
     */
    private void insertFileData(TemplateRo templateRo, Template template) {
        String fileData = templateRo.getFileData();
        //todo 生成html 上传文件系统
        TemplateExt templateExt = new TemplateExt();
        templateExt.setExtName(ManagerConstant.FTL);
        templateExt.setTemplateData(fileData.getBytes());
        templateExt.setCreateTime(new Date());
        templateExt.setUpdateTime(new Date());
        templateExtMapper.insertFile(templateExt);
        Integer id = templateExt.getId();
        template.setRefId(id);
    }

    /**
     * 查询审核状态
     *
     * @return
     */
    public List<DictionaryVo> queryAuditStatus() {
        List<Dictionary> dictionaryPos = dictionaryService.selectByType(ManagerConstant.AUDIT_STATUS);
        List<DictionaryVo> list = new ArrayList<>();
        dictionaryPos.forEach(po -> {
            DictionaryVo vo = new DictionaryVo();
            BeanUtils.copyProperties(po, vo);
            list.add(vo);
        });
        return list;
    }

    /**
     * 更新历史表
     *
     * @param template
     */
    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.REQUIRED)
    public void updateTemplateHistory(Template template) {
        TemplateHistory templateHistoryPo = new TemplateHistory();
        BeanUtils.copyProperties(template, templateHistoryPo);
        //查询历史模板内容
        Template po = templateMapper.selectByPrimaryKey(template.getId());
        templateHistoryPo.setId(null);
        Integer sealType = po.getSealType();
        if (sealType != 1) {
            OfficialSealTemplate officialSealTemplate = new OfficialSealTemplate();
            officialSealTemplate.setTemplateNo(po.getTemplateNo());
            List<OfficialSealTemplate> officialSealTemplates = officialSealTemplateService.selectByExample(officialSealTemplate);
            for (OfficialSealTemplate sealTemplate : officialSealTemplates) {
                HistoryOfficialSealTemplate history = new HistoryOfficialSealTemplate();
                history.setTemplateNo(sealTemplate.getTemplateNo());
                history.setOfficialSealCode(sealTemplate.getOfficialSealCode());
                history.setVersion(po.getVersion());
                historyOfficialSealTemplateMapper.insert(history);
            }
        }
        templateHistoryPo.setTemplateName(po.getTemplateName());
        templateHistoryPo.setRefId(po.getRefId());
        templateHistoryPo.setRemark(po.getRemark());
        templateHistoryPo.setCreateId(po.getCreateId());
        templateHistoryPo.setCreateName(po.getCreateName());
        templateHistoryPo.setChannelId(po.getChannelId());
        templateHistoryPo.setTemplateStatus(ManagerConstant.DISABLE);
        templateHistoryPo.setCreateTime(po.getCreateTime());
        templateHistoryPo.setUpdateTime(po.getUpdateTime());
        templateHistoryMapper.insert(templateHistoryPo);
    }

    /**
     * 更新公章规则号
     *
     * @param officialSealId
     * @param templateNo
     */
    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.REQUIRED)
    public void updateOfficialSeal(String[] officialSealId, String templateNo) {
        if (officialSealId == null) {
            throw new RuntimeException("公章规则号为空");
        }
        //先删除再更新
        OfficialSealTemplate officialSealTemplate = new OfficialSealTemplate();
        officialSealTemplate.setTemplateNo(templateNo);
        officialSealTemplateService.deleteByExample(officialSealTemplate);
        for (String sealCode : officialSealId) {
            OfficialSealTemplate sealTemplate = new OfficialSealTemplate();
            sealTemplate.setTemplateNo(templateNo);
            sealTemplate.setOfficialSealCode(sealCode);
            officialSealTemplateService.insert(sealTemplate);
        }
    }


    //----------------------------------------工具方法----------------------------------------

    private List<TemplateVo> buildPos(List<Template> templates) {
        List<TemplateVo> list = new ArrayList<>();
        templates.forEach(po -> {
            TemplateVo templateVo = new TemplateVo();
            //创建人、修改人 + ehrId
            templateVo.setWholeCreateName(po.getCreateName() + "/" + po.getCreateId());
            if (StringUtils.isNotBlank(po.getOperatorName())) {
                templateVo.setWholeOperatorName(po.getOperatorName() + "/" + po.getOperatorId());
            }
            list.add(convertPotoVo(po, templateVo));
        });
        return list.parallelStream().sorted(Comparator.comparing(TemplateVo::getTemplateNo)).collect(Collectors.toList());
    }

    private TemplateVo convertPotoVo(Template po, TemplateVo templateVo) {
        BeanUtils.copyProperties(po, templateVo);
        templateVo.setApprovalId(po.getApprovalId() + "");
        //签章类型
        if (po.getSealType() != null) {
            String name = dictionaryService.selectOneByTypeAndCode(ManagerConstant.SEAL_TYPE, po.getSealType().toString());
            templateVo.setSealTypeName(name);
        }
        //模板来源
        if (po.getResource() != null) {
            String name = dictionaryService.selectOneByTypeAndCode(ManagerConstant.RESOURCE_TYPE, po.getResource().toString());
            templateVo.setResourceName(name);
        }
        //是否启用
        if (po.getTemplateStatus() != null) {
            String name = dictionaryService.selectOneByTypeAndCode(ManagerConstant.COMMON_STATUS, po.getTemplateStatus().toString());
            //状态为2时也为停用状态
            if (StringUtils.isNotBlank(name)) {
                templateVo.setTemplateStatusName("停用");
            }
            templateVo.setTemplateStatusName(name);
        }
        //审核状态
        if (po.getAuditStatus() != null) {
            String name = dictionaryService.selectOneByTypeAndCode(ManagerConstant.AUDIT_STATUS, po.getAuditStatus().toString());
            templateVo.setAuditStatusName(name);
        }
        //渠道编号
        if (po.getChannelId() != null) {
            Channel channel = channelService.selectChannelByCode(po.getChannelId().toString());
            if (channel != null) {
                templateVo.setChannelId(Integer.valueOf(channel.getChannelNo()));
                templateVo.setChannelName(channel.getChannelName());
            }
        }
        //公章规则号
        if (StringUtils.isNotEmpty(po.getTemplateNo())) {
            OfficialSealTemplate officialSealTemplate = new OfficialSealTemplate();
            officialSealTemplate.setTemplateNo(po.getTemplateNo());
            List<OfficialSealTemplate> poList = officialSealTemplateService.selectByExample(officialSealTemplate);
            if (poList.size() > 0) {
                StringBuilder bd = new StringBuilder();
                poList.forEach(item -> bd.append(item.getOfficialSealCode()).append(","));
                templateVo.setOfficialSealId(bd.substring(0, bd.lastIndexOf(",")));
            }
        }
        //模板内容
        if (ManagerConstant.ONLINE.equals(po.getResource())) {
            if (po.getRefId() != null) {
                TemplateExt templateExt = templateExtMapper.selectByPrimaryKey(po.getRefId());
                byte[] templateData = templateExt.getTemplateData();
                templateVo.setFileData(new String(templateData));
            }
        }
        //模板类型
        String vipValue = dictionaryService.selectOneByTypeAndCode(ManagerConstant.IS_VIP, String.valueOf(po.getVip()));
        templateVo.setVip(vipValue);

        return templateVo;
    }

    /**
     * 封装响应头
     *
     * @param response
     * @param fileName
     */
    private void buildResponse(HttpServletResponse response, String fileName) {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), StandardCharsets.ISO_8859_1));
        response.setHeader("Access-Control-Allow-Origin", "POST,GET,PUT,OPTIONS,DELETE");
    }

    /**
     * 封装文件名称
     *
     * @param ids
     * @param templateExt
     * @return
     */
    private String buildFileName(String ids, TemplateExt templateExt, String className) {
        String templateNo = null;
        String templateName = null;
        if (className.equals(Template.class.getSimpleName())) {
            Template template = new Template();
            template.setRefId(Integer.valueOf(ids));
            template.setVip(null);
            Map<String, Object> params = ManagerBeanUtil.buildQueryParams(template);
            List<Template> templates = templateMapper.selectByExample(params.get(ManagerConstant.EXAMPLE));
            Template template1 = templates.get(0);
            templateName = template1.getTemplateName();
            templateNo = template1.getTemplateNo();
        } else {
            TemplateHistory templateHistory = new TemplateHistory();
            templateHistory.setRefId(Integer.valueOf(ids));
            Map<String, Object> params = ManagerBeanUtil.buildQueryParams(templateHistory);
            TemplateHistory templateHistory1 = templateHistoryMapper.selectOneByExample(params.get(ManagerConstant.EXAMPLE));
            templateName = templateHistory1.getTemplateName();
            templateNo = templateHistory1.getTemplateNo();
        }
        return templateNo + "-" + templateName + "." + templateExt.getExtName();
    }

    /**
     * 查询公章规则号--
     *
     * @param templateNo
     * @return
     */
    public List<DictionaryVo> queryOfficialSealById(String templateNo) {
        OfficialSealTemplate officialSealTemplate = new OfficialSealTemplate();
        officialSealTemplate.setTemplateNo(templateNo);
        List<OfficialSealTemplate> officialSealTemplates = officialSealTemplateService.selectByExample(officialSealTemplate);
        List<DictionaryVo> list = new ArrayList<>();
        officialSealTemplates.stream().forEach(po -> {
            DictionaryVo vo = new DictionaryVo();
            String officialSealCode = po.getOfficialSealCode();
            String name = dictionaryService.selectOneByTypeAndCode(ManagerConstant.OFFICIAL_TYPE, officialSealCode);
            if (StringUtils.isNotEmpty(name)) {
                vo.setCode(officialSealCode);
                vo.setName(name);
            } else {
                SealInfo sealInfo = sealInfoService.selectBySealCode(officialSealCode);
                if (sealInfo != null) {
                    vo.setCode(officialSealCode);
                    vo.setName(sealInfo.getKeyWords());
                } else {
                    FddSealInfo sealInfoParams = new FddSealInfo();
                    sealInfoParams.setSealCode(officialSealCode);
                    Map<String, Object> params = ManagerBeanUtil.buildQueryParams(sealInfoParams);
                    FddSealInfo fddSealInfo = fddSealInfoMapper.selectOneByExample(params.get(ManagerConstant.EXAMPLE));
                    vo.setCode(officialSealCode);
                    vo.setName(fddSealInfo.getKeyWords());
                }
            }
            list.add(vo);
        });
        return list;
    }

    public List<DictionaryVo> queryHistoryOfficialSealById(TemplateRo templateRo) {

        HistoryOfficialSealTemplate history = new HistoryOfficialSealTemplate();
        history.setTemplateNo(templateRo.getTemplateNo());
        history.setVersion(templateRo.getVersion());
        Map<String, Object> params = ManagerBeanUtil.buildQueryParams(history);
        List<HistoryOfficialSealTemplate> historyOfficialSealTemplates = historyOfficialSealTemplateMapper.selectByExample(params.get(ManagerConstant.EXAMPLE));
        List<DictionaryVo> list = new ArrayList<>();
        historyOfficialSealTemplates.stream().forEach(po -> {
            DictionaryVo vo = new DictionaryVo();
            String officialSealCode = po.getOfficialSealCode();
            String name = dictionaryService.selectOneByTypeAndCode(ManagerConstant.OFFICIAL_TYPE, officialSealCode);
            if (StringUtils.isNotEmpty(name)) {
                vo.setCode(officialSealCode);
                vo.setName(name);
            } else {
                SealInfo sealInfo = sealInfoService.selectBySealCode(officialSealCode);
                vo.setCode(officialSealCode);
                vo.setName(sealInfo.getKeyWords());
            }
            list.add(vo);
        });
        return list;

    }


    /**
     * 修改模板状态
     *
     * @param templateRo
     */
    @Transactional(rollbackFor = RuntimeException.class, propagation = Propagation.REQUIRED)
    public void updateTemplateSts(TemplateRo templateRo) {
        Template template = new Template();
        template.setId(templateRo.getId());
        template.setTemplateStatus(templateRo.getTemplateStatus());
        templateMapper.updateByPrimaryKeySelective(template);
    }

    /**
     * 修改模板审核状态
     *
     * @param templateRo
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateAuditSts(TemplateRo templateRo) {
        Template template = new Template();
        BeanUtils.copyProperties(templateRo, template);
        if (templateRo.getAuditStatus() != null && templateRo.getAuditStatus().equals(ManagerConstant.AUDITPASS)) {
            template.setTemplateStatus(ManagerConstant.Enable);
        }
        template.setUpdateTime(new Date());
        Example example = new Example(Template.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", templateRo.getId());
        criteria.andEqualTo("approvalId", template.getApprovalId());
        templateMapper.updateByExampleSelective(template, example);

        //审批通过时，删除模板表里模板编号与当前编号相同且id不同的模板数据
        if (ManagerConstant.AUDITPASS.equals(templateRo.getAuditStatus())) {
            Template template1 = templateMapper.selectByPrimaryKey(templateRo.getId());
            if (template1 != null && StringUtils.isNotBlank(template1.getTemplateNo())) {
                Example example1 = new Example(Template.class);
                Example.Criteria criteria1 = example1.createCriteria();
                criteria1.andEqualTo("templateNo", template1.getTemplateNo());
                criteria1.andNotEqualTo("id", templateRo.getId());
                if (StringUtils.isNotBlank(template1.getTemplateNo())) {
                    templateMapper.deleteByExample(example1);
                }
            }
            //审批拒绝时。删除模板表当前id的数据
        } else if (ManagerConstant.AUDITREJECT.equals(templateRo.getAuditStatus())) {
            Template template1 = templateMapper.selectByPrimaryKey(templateRo.getId());
            if (template1 == null) {
                return;
            }
            Example example1 = new Example(Template.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andEqualTo("templateNo", template1.getTemplateNo());
            List<Template> templates = templateMapper.selectByExample(example1);
            if (templates.size() > 1 && StringUtils.isNotBlank(template1.getTemplateNo())) {
                templateMapper.deleteByPrimaryKey(templateRo.getId());
            }
        }
    }

    /**
     * 查询所有--历史模板
     *
     * @param templateRo
     * @return
     */
    public PageInfo<TemplateVo> queryAllHistory(TemplateRo templateRo) {
        if (StringUtils.isNotBlank(templateRo.getChannelIds())) {
            log.info("查询所有历史模板channelIds=[" + templateRo.getChannelIds() + "]");
            PageUtils.setPageNo(templateRo);
            List<TemplateHistory> templateHistories = templateHistoryMapper.listByParamsAndPage(templateRo);
            int count = templateHistoryMapper.countByParamsAndPage(templateRo);
            //TemplateHistory转换成Template之后再封装成TemplateVo
            List<Template> templates = new ArrayList<>();
            templateHistories.forEach(po -> {
                Template template = new Template();
                BeanUtils.copyProperties(po, template);
                templates.add(template);
            });
            List<TemplateVo> vos = buildPos(templates);
            return new PageInfo<>(vos, count, templateRo.getPageNo(), templateRo.getPageSize());
        } else {
            return new PageInfo<>(null, 0, templateRo.getPageNo(), templateRo.getPageSize());
        }
    }

    /**
     * 查询单条--历史模板
     *
     * @param id
     * @return
     */
    public TemplateVo queryOneHistory(Long id) {
        TemplateHistory templateHistory = templateHistoryMapper.selectByPrimaryKey(id);
        Template template = new Template();
        BeanUtils.copyProperties(templateHistory, template);
        TemplateVo templateVo = new TemplateVo();
        templateVo = convertPotoVo(template, templateVo);
        //设置公章规则号
        if (StringUtils.isNotEmpty(template.getTemplateNo())) {
            HistoryOfficialSealTemplate history = new HistoryOfficialSealTemplate();
            history.setTemplateNo(template.getTemplateNo());
            history.setVersion(template.getVersion());
            Map<String, Object> params = ManagerBeanUtil.buildQueryParams(history);
            List<HistoryOfficialSealTemplate> poList = historyOfficialSealTemplateMapper.selectByExample(params.get(ManagerConstant.EXAMPLE));
            if (poList.size() > 0) {
                StringBuilder bd = new StringBuilder();
                poList.forEach(item -> bd.append(item.getOfficialSealCode()).append(","));
                templateVo.setOfficialSealId(bd.substring(0, bd.lastIndexOf(",")));
            }
        }
        return templateVo;
    }


}
